package info.itest.www.pages;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import info.itest.www.pages.*;

public class PostFormPage extends BasePage {
	
	final String createPostUrl =  "http://localhost/wordpress/wp-admin/post-new.php";
	//final String url = "http://localhost/wordpress/wp-admin/post-new.php"; 
	public PostFormPage(WebDriver dr){
		super(dr);
		
		
	}
	
	
	By titleLocator = By.name("post_title");
	By publishBtnLocator = By.id("publish");
	By permalLinkLocator = By.id("sample-permalink");
	
	
	public void setContent(String content) {

		String js = "document.getElementById('content_ifr').contentWindow.document.body.innerHTML='"
				+ content + "'";
		((JavascriptExecutor) dr).executeScript(js);
		
	}
	
	public WebElement getTitleTextFiled(){
		return this.dr.findElement(titleLocator);
	}
	
	public WebElement getPublishBtn(){
		return this.dr.findElement(publishBtnLocator);
	}
	
	public WebElement getPermalLink(){
	return this.dr.findElement(permalLinkLocator);
}
    public String createPost(String title,String content){
		
		this.dr.get(createPostUrl);
		this.doCreatePost(title, content);
		return this.fetchPostId();
    	//this.goTo();
		//String title = "Test title" + System.currentTimeMillis();
		//this.dr.findElement(By.name("post_title")).clear();
		//this.dr.findElement(By.name("post_title")).sendKeys(title);
//		this.getTitleTextFiled().clear();
//		this.getTitleTextFiled().sendKeys(title);
//		this.setContent(null);
//		this.setContent(content);
		//dr.findElement(By.name("publish")).click(); 
//		this.getPublishBtn().click();
//		return this.fetchPostId();
	}
	
	public String fetchPostId(){
		//String postUrl = this.dr.findElement(By.id("sample-permalink")).getText();
		String postUrl = this.getPermalLink().getText();
		String[] arr = postUrl.split("=");
		return arr[1];
	}
	
	public String createPost(){
		String title = "Test title" + System.currentTimeMillis();
		String content = "Test Content" + System.currentTimeMillis();
		return this.createPost(title,content);

	}
	
	public String createPost(String title){
		String content = "test Content" + System.currentTimeMillis();
		return this.createPost(title,content);
	}
	
	public void doCreatePost(String title,String content){
		
		this.getTitleTextFiled().clear();
		this.getTitleTextFiled().sendKeys(title);
		this.setContent(null);
		this.setContent(content);
		this.getPublishBtn().click();
		//return this.fetchPostId();
	}
	
	
}
